const express = require('express');
const fs = require('fs-extra');
const path = require('path');
const gitService = require('../services/gitService');

const router = express.Router();
const configPath = path.join(__dirname, '../config/default.json');

// 获取配置
router.get('/', async (req, res) => {
  try {
    const config = await fs.readJson(configPath);
    
    // 隐藏敏感信息
    const safeConfig = {
      ...config,
      webhook: {
        ...config.webhook,
        secret: config.webhook.secret ? '***已设置***' : ''
      }
    };
    
    res.json({
      success: true,
      data: safeConfig
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '读取配置失败',
      error: error.message
    });
  }
});

// 更新配置
router.put('/', async (req, res) => {
  try {
    const currentConfig = await fs.readJson(configPath);
    const newConfig = { ...currentConfig, ...req.body };
    
    // 验证必要字段
    if (!newConfig.server || !newConfig.git) {
      return res.status(400).json({
        success: false,
        message: '配置格式不正确'
      });
    }
    
    // 如果webhook secret是占位符，保持原值
    if (newConfig.webhook?.secret === '***已设置***') {
      newConfig.webhook.secret = currentConfig.webhook.secret;
    }
    
    await fs.writeJson(configPath, newConfig, { spaces: 2 });
    
    res.json({
      success: true,
      message: '配置更新成功',
      data: newConfig
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新配置失败',
      error: error.message
    });
  }
});

// 重置配置为默认值
router.post('/reset', async (req, res) => {
  try {
    const defaultConfig = {
      "server": {
        "port": 3000,
        "host": "0.0.0.0"
      },
      "webhook": {
        "secret": "",
        "path": "/webhook"
      },
      "git": {
        "targetBranch": "main",
        "repositoryUrl": "",
        "localPath": "./temp/repo",
        "deployPath": "./public/dist"
      },
      "build": {
        "commands": [
          "npm install",
          "npm run build"
        ],
        "timeout": 300000
      },
      "service": {
        "name": "web-service",
        "restartCommand": "pm2 restart web-service"
      },
      "logging": {
        "level": "info",
        "file": "./logs/app.log",
        "maxFiles": 10,
        "maxSize": "10m"
      }
    };
    
    await fs.writeJson(configPath, defaultConfig, { spaces: 2 });
    
    res.json({
      success: true,
      message: '配置已重置为默认值',
      data: defaultConfig
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '重置配置失败',
      error: error.message
    });
  }
});

// 验证配置
router.post('/validate', async (req, res) => {
  try {
    const config = req.body;
    const errors = [];
    
    // 验证服务器配置
    if (!config.server?.port || config.server.port < 1 || config.server.port > 65535) {
      errors.push('服务器端口必须在1-65535之间');
    }
    
    // 验证Git配置
    if (!config.git?.targetBranch) {
      errors.push('目标分支不能为空');
    }
    
    if (!config.git?.repositoryUrl) {
      errors.push('仓库URL不能为空');
    }
    
    // 验证Git认证配置
    if (config.git?.auth?.enabled) {
      const authType = config.git.auth.type;
      
      if (!['ssh', 'token', 'password'].includes(authType)) {
        errors.push('认证类型必须是ssh、token或password之一');
      } else {
        if (authType === 'ssh' && !config.git.auth.sshKeyPath) {
          errors.push('SSH认证需要配置密钥路径');
        } else if (authType === 'token' && !config.git.auth.token) {
          errors.push('Token认证需要配置访问令牌');
        } else if (authType === 'password' && (!config.git.auth.username || !config.git.auth.password)) {
          errors.push('密码认证需要配置用户名和密码');
        }
      }
    }
    
    // 验证构建配置
    if (!config.build?.commands || !Array.isArray(config.build.commands)) {
      errors.push('构建命令必须是数组');
    }
    
    if (config.build?.timeout && (config.build.timeout < 10000 || config.build.timeout > 1800000)) {
      errors.push('构建超时时间必须在10秒到30分钟之间');
    }
    
    res.json({
      success: errors.length === 0,
      message: errors.length === 0 ? '配置验证通过' : '配置验证失败',
      errors
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '验证配置失败',
      error: error.message
    });
  }
});

// 验证Git认证配置
router.post('/validate-auth', async (req, res) => {
  try {
    // 临时更新配置以进行验证
    const originalConfig = require('../config/default.json');
    const tempConfig = { ...originalConfig, git: { ...originalConfig.git, auth: req.body } };
    
    // 临时写入配置文件
    const tempConfigPath = path.join(__dirname, '../config/temp.json');
    await fs.writeJson(tempConfigPath, tempConfig, { spaces: 2 });
    
    // 重新加载gitService以使用新配置
    delete require.cache[require.resolve('../config/default.json')];
    delete require.cache[require.resolve('../services/gitService')];
    
    const tempGitService = require('../services/gitService');
    const validation = await tempGitService.validateAuthConfig();
    
    // 清理临时文件
    await fs.remove(tempConfigPath);
    
    // 恢复原始配置
    delete require.cache[require.resolve('../config/default.json')];
    delete require.cache[require.resolve('../services/gitService')];
    
    res.json({
      success: validation.valid,
      message: validation.message,
      valid: validation.valid
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '验证认证配置失败',
      error: error.message,
      valid: false
    });
  }
});

module.exports = router;